import { routes } from "@/router";
import { ProCard, ProLayout, ProSettings } from "@ant-design/pro-components";
import { Avatar, Dropdown, MenuProps } from "antd";
import { Suspense, useContext, useEffect, useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router";
import MenuHeaderRender from "./menuHeaderRender";
import SwitchThemeAnimate from "@/components/switchThemeAnimate";
import { ThemeContext } from "@/App";
import config from "../../config";
import { onRouteChange } from "@/utils/request";
import FullScreen from "@/components/fullScreen";
import { useAliveController } from "react-activation";
import { inject, observer } from "mobx-react";
import { ITabsStore } from "@/store/tabsStore";
import classNames from "classnames";
import { IRoute } from "@/vite-env";
import { getCurrentRoute } from "@/utils/tools";
import treeRouter from "@/router/handleRoute";
const Layout = ({ tabsStore }: { tabsStore?: ITabsStore }) => {
  const { dropScope, getCachingNodes } = useAliveController();
  const history = useNavigate();
  const [collapsed, setCollapsed] = useState(false);
  const [settings] = useState<Partial<ProSettings> | undefined>({
    fixSiderbar: true,
    siderMenuType: "sub",
    layout: "side",
    splitMenus: false
  });
  const location = useLocation();
  const { setIsDark } = useContext(ThemeContext);
  const pageConfig = config();
  const logout = () => {
    localStorage.clear();
    sessionStorage.clear();
    window.location.replace("/login");
  };
  const [router, setRouter] = useState<IRoute>(null);

  const maxKeepAlive = pageConfig.maxKeepAlive;

  useEffect(() => {
    const curRouter = getCurrentRoute(treeRouter, location.pathname);
    setRouter(curRouter);
    document.title = curRouter?.meta?.name || "后台管理系统";
    if (!curRouter?.meta?.isStaticPage) {
      tabsStore.setVisitedViewsTabs(curRouter);
    }
    if (getCachingNodes().length >= maxKeepAlive) {
      const dropItem = getCachingNodes()[0];
      dropScope(dropItem.name);
    }
  }, [location]);
  const items: MenuProps["items"] = [
    {
      key: "1",
      label: (
        <a target="_blank" rel="noopener noreferrer" onClick={logout}>
          退出登录
        </a>
      )
    }
  ];
  const closeVisitedViewsTabs = (item: IRoute) => {
    tabsStore.removeVisitedViewsTabs(item.path);
    if (tabsStore.visitedViewsTabs.length == 0) {
      tabsStore.setVisitedViewsTabs(router);
    }
    const curTab = tabsStore.visitedViewsTabs[tabsStore.visitedViewsTabs.length - 1];
    history({ pathname: curTab.path }, { replace: true });
    setTimeout(() => {
      dropScope(item.path);
    }, 0);
  };

  return (
    <>
      {router && router?.meta?.noLayout ? (
        <Suspense>
          <Outlet />
        </Suspense>
      ) : (
        <ProLayout
          menuItemRender={(item, dom: any) => {
            return (
              <div
                className={dom.props.className}
                onClick={() => {
                  history({ pathname: item.path });
                }}
              >
                <i className={[item?.icon, dom.props.children?.[0]?.props?.className].join(" ")}></i>
                {!collapsed ? <span className={dom.props.children?.[1]?.props?.className}>{item.name}</span> : null}
              </div>
            );
          }}
          token={{
            sider: {
              colorMenuBackground: "var(--vp-c-bg)",
              colorBgMenuItemHover: "var(--vp-menu-hover-color)",
              colorTextMenuSelected: "var(--vp-text-select-color)",
              colorTextMenuActive: "var(--vp-menu-active-color)"
            }
          }}
          onPageChange={(location) => {
            onRouteChange({ location });
          }}
          collapsed={collapsed}
          collapsedButtonRender={() => {
            return (
              <div className="f-c-c justify-between" onClick={() => setCollapsed(!collapsed)}>
                {!collapsed ? (
                  <i className="i-mdi-light:format-indent-decrease h-40 font-size-25 cursor-pointer"></i>
                ) : (
                  <i className="i-mdi-light:format-indent-increase h-40 font-size-25 cursor-pointer"></i>
                )}
              </div>
            );
          }}
          subMenuItemRender={(item, dom: any) => (
            <div className={dom.props.className}>
              <i className={[item?.icon, dom.props.children?.[0]?.props?.className].join(" ")}></i>
              <span className={dom.props.children?.[1]?.props?.className}>{item.name}</span>
            </div>
          )}
          title={pageConfig.title}
          logo="https://gw.alipayobjects.com/mdn/rms_b5fcc5/afts/img/A*1NHAQYduQiQAAAAAAAAAAABkARQnAQ"
          menuHeaderRender={(logo, title) => <MenuHeaderRender logo={logo} title={title} />}
          route={routes}
          location={{
            pathname: location.pathname
          }}
          {...settings}
        >
          <div
            className="flex items-center pr-20 pl-20"
            style={{ height: "52px", width: "100%", backgroundColor: "var(--vp-c-bg)" }}
          >
            <div className="ml-auto flex items-center gap-10 transform-translate-y-2">
              <FullScreen />
              <SwitchThemeAnimate setIsDark={setIsDark} />
            </div>
            <div className="h-20">
              <Dropdown menu={{ items }} trigger={["click"]} arrow>
                <div className="flex items-center cursor-pointer">
                  <Avatar
                    className="ml-20 transform-translate-y--2"
                    size="small"
                    src="https://api.dicebear.com/7.x/miniavs/svg?seed=2"
                  />
                  <span>成爸爸</span>
                </div>
              </Dropdown>
            </div>
          </div>
          <div p="l-20 r-20" className="w-full h-40 bg-active flex items-center gap-8">
            {tabsStore.visitedViewsTabs.map((item) => {
              return (
                <div
                  p="l-5 r-5"
                  className={classNames([
                    "h-30 flex items-center cursor-pointer  rounded-5 transition-all duration-100",
                    location?.pathname == item?.path ? "a-box-style" : "normal-box-style"
                  ])}
                  key={item?.path}
                >
                  <span className="transform-translate-y--1" onClick={() => history(item?.path)}>
                    {item?.name}
                  </span>
                  {location?.pathname == item?.path && !router?.meta?.fixed && (
                    <i
                      className="i-line-md:close-small ml-5 vertical-align-middle"
                      onClick={() => closeVisitedViewsTabs(item)}
                    ></i>
                  )}
                </div>
              );
            })}
          </div>

          <div
            style={{
              margin: "15px",
              height: "calc(100vh - 125px)"
            }}
          >
            <ProCard>
              <Outlet />
            </ProCard>
          </div>
        </ProLayout>
      )}
    </>
  );
};
export default inject("tabsStore")(observer(Layout));
